package com.lxr.test5002.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;

public class SharedPreferencesUtils {

    private static final String SPNAME_BASEINFO = "App_ConfigInfo";
    private static SharedPreferencesUtils sSharedPreferencesUtils;
    private static Context sContext;
    private static SharedPreferences.Editor sEditor;
    private static SharedPreferences sSharedPreferences;

    private SharedPreferencesUtils(){}

    @SuppressLint("CommitPrefEdits")
    public static SharedPreferencesUtils getInstance(Context context){
        sContext = context;
        if (sSharedPreferencesUtils == null) {
            sSharedPreferencesUtils = new SharedPreferencesUtils();
        }
        if (sEditor == null||sSharedPreferences ==null) {
            sSharedPreferences = sContext
                    .getSharedPreferences(SPNAME_BASEINFO, Context.MODE_PRIVATE);
            sEditor = sSharedPreferences.edit();
        }
        return sSharedPreferencesUtils;

    }

    /**
     * 保存数据到文件
     * @param key
     * @param data
     */
    public void saveData( String key, String data){
        sEditor.putString(key, data);
        sEditor.apply();
    }

    /**
     * 删除保存的数据
     * @param key
     */
    public void deleteData(String key){
        sEditor.remove(key);
        sEditor.apply();
    }

    /**
     * 从文件中读取数据
     * @param key
     * @param defValue
     * @return
     */
    public String getData(String key, String defValue){
        return sSharedPreferences.getString(key, defValue);
    }
}
